﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using umbraco.cms.presentation.Trees;
using umbraco.interfaces;
using umbraco.controls;
using umbraco.cms.businesslogic.language;
using Commerce.Common;

namespace CommerceForUmbraco.adminSection.trees
{
    public class loadCouponTree : BaseTree
    {
        public loadCouponTree(string application) : base(application) { }

        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
                rootNode.Icon = FolderIcon;
                rootNode.OpenIcon = FolderIconOpen;
                rootNode.NodeType = "init" + TreeAlias;
                rootNode.NodeID = "init";
        }

        public override void Render(ref XmlTree tree)
        {
            // get collection values
            Commerce.Common.CouponCollection coupons = null;

            coupons = new CouponCollection().OrderByAsc("CouponCode").Load();

            foreach (Coupon thisCoupon in coupons)
	        {
                              
                XmlTreeNode xNode = XmlTreeNode.Create(this);
                xNode.NodeID = thisCoupon.CouponCode.ToString();
                xNode.Text = thisCoupon.CouponCode;
                xNode.Action = "javascript:openCoupon('" + thisCoupon.CouponCode + "');";

                if ((thisCoupon.IsSingleUse && thisCoupon.NumberUses > 0))
                {
                    xNode.Icon = "coupon_expired.gif";
                    xNode.OpenIcon = "coupon_expired.gif";
                }
                else
                {
                    if (thisCoupon.ExpirationDateHasValue)
                    {
                        if (thisCoupon.ExpirationDate < DateTime.UtcNow)
                        {
                            xNode.Icon = "coupon_expired.gif";
                            xNode.OpenIcon = "coupon_expired.gif";
                        }
                        else
                        {
                            xNode.Icon = "coupon.gif";
                            xNode.OpenIcon = "coupon.gif";
                        }
                    }
                    else
                    {
                        xNode.Icon = "coupon.gif";
                        xNode.OpenIcon = "coupon.gif";
                    }
                }
                tree.Add(xNode);
	        }

        }

        public override void RenderJS(ref StringBuilder Javascript)
        {
                 Javascript.Append(
                    @"
                    function openCoupon(id) {
	                    parent.right.document.location.href = 'commerce/editCoupon.aspx?c=' + id;
                    }
                ");
        }
    }
}
